<template>
  <div class="loginav">
    <div class="video"><video src="../assets/images/video.mp4" muted autoplay loop></video></div>
    <div class=""></div>
    <div class="loginbox boxall">
      <div class="logo">
        <h1>智慧AI创新平台</h1>
        <h2>zhi hui AI chuang xin pin tai</h2>
        <!-- <img src="images/logo.png"> -->
      </div>
      <div class="logintit">用户登录</div>
      <ul class="logininput">
        <li>
          <i><img src="../assets/images/user.png"></i>
          <input class="forminput" v-model="username" type="text" placeholder="用户名">
        </li>
        <li>
          <i><img src="../assets/images/password.png"></i>
          <input class="forminput" v-model="password" type="password" placeholder="密码">
        </li>

        <div class=" flex1" style="padding: 15px 0;">
          <label> <input type="checkbox" v-model="rememberPassword" class="aui-checkbox">&nbsp;记住密码</label>
          <a href="#" class="text-primary"> 忘记密码？</a>
        </div>
        <li>
          <div class="btn-row">
            <a href="#" class="btn btnblock btn-lg btn-block btn-primary" @click.prevent="handleLogin">登录</a>
            <a href="#" class="btn btnblock btn-lg btn-block btn-primary" @click="handleRegister">注册</a>
          </div>
        </li>
      </ul>
      <div class="boxfoot"></div>
    </div>
  </div>
  <div class="copyright">版权所有：All Right By <a href="http://www.bootstrapmb.com">Reserved</a> 2022-2022</div>

  <canvas id='canvas'
          style="position:fixed; width:100%; height:100%; left: 0; top: 0; opacity: .3; pointer-events: none;"></canvas>

  <!-- 注册弹窗 -->
  <MyDialog v-model="showRegister" title="请注册" :width="'720px'" :showFooter="false">
    <div class="register-wrap">
      <div class="logintit">请注册</div>
      <ul class="logininput">
        <li>
          <i><img src="../assets/images/user.png"></i>
          <input class="forminput" v-model="registerForm.mobile" type="text" placeholder="请输入手机号">
        </li>
        <li>
          <i><img src="../assets/images/user.png"></i>
          <div class="verify-row">
            <input class="forminput" v-model="registerForm.code" type="text" placeholder="请输入验证码">
            <a href="#" class="btn btn-primary send-btn" @click.prevent="handleSendCode">发送验证码</a>
          </div>
        </li>
        <li>
          <i><img src="../assets/images/password.png"></i>
          <input class="forminput" v-model="registerForm.password" type="password" placeholder="请输入密码">
        </li>
        <li>
          <i><img src="../assets/images/password.png"></i>
          <input class="forminput" v-model="registerForm.re_password" type="password" placeholder="请再次输入密码">
        </li>
        <li>
          <i><img src="../assets/images/user.png"></i>
          <div class="verify-row">
            <select class="forminput" v-model="selectedProvinceCode">
              <option :value="''" disabled>请选择省</option>
              <option v-for="item in provinceOptions" :key="item.code" :value="item.code">{{ item.name }}</option>
            </select>
            <select class="forminput" v-model="selectedCityCode" :disabled="!selectedProvinceCode">
              <option :value="''" disabled>请选择市</option>
              <option v-for="item in cityOptions" :key="item.code" :value="item.code">{{ item.name }}</option>
            </select>
            <select class="forminput" v-model="selectedAreaCode" :disabled="!selectedCityCode">
              <option :value="''" disabled>请选择区/县</option>
              <option v-for="item in areaOptions" :key="item.code" :value="item.code">{{ item.name }}</option>
            </select>
          </div>
        </li>
        <li>
          <i><img src="../assets/images/user.png"></i>
          <input class="forminput" v-model="registerForm.bzid" type="text" placeholder="请输入邀请码">
        </li>
        <li>
          <div class="btn-row">
            <a href="#" class="btn btnblock btn-lg btn-block btn-primary" @click.prevent="handleRegisterSubmit">确定提交</a>
          </div>
        </li>
      </ul>
    </div>
  </MyDialog>
</template>
<script setup lang="ts">
import { onMounted, ref, computed,nextTick, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import axiosUtil from '../axios-util/axios-util'
import utils from '../utils/utils'
import LocalStorageUtil from '../utils/LocalStorageUtil'
import MyDialog from './common/MyDialog.vue'

const router = useRouter()
const username = ref('')
const password = ref('')
const rememberPassword = ref(false)
const showRegister = ref(false)

const registerForm = reactive({
  mobile: '',
  code: '',
  password: '',
  re_password: '',
  region: '',
  bzid: '',
  province: '',
  city: '',
  area: ''
})

// 从localStorage中获取保存的用户名和密码
onMounted(() => {
  document.body.classList.add('login-page');
  init();

  // 检查是否有保存的登录信息
  const savedUsername:string = LocalStorageUtil.get('username')
  const savedPassword:string = LocalStorageUtil.get('password')
  if (savedUsername && savedPassword) {
    username.value = savedUsername
    password.value = savedPassword
    rememberPassword.value = true
  }
})

const pcaData = ref<any[]>([])

// 省市区选中值（使用 code 关联）
const selectedProvinceCode = ref<string>('')
const selectedCityCode = ref<string>('')
const selectedAreaCode = ref<string>('')

// 选项计算
const provinceOptions = computed(() => {
  return (pcaData.value || []) as Array<{ code: number | string; name: string; children?: any[] }>
})

const cityOptions = computed(() => {
  if (!selectedProvinceCode.value) return [] as Array<{ code: number | string; name: string; children?: any[] }>
  const province = provinceOptions.value.find(p => String(p.code) === String(selectedProvinceCode.value))
  return province?.children || []
})

const areaOptions = computed(() => {
  if (!selectedCityCode.value) return [] as Array<{ code: number | string; name: string }>
  const city = cityOptions.value.find(c => String(c.code) === String(selectedCityCode.value))
  return city?.children || []
})

// 监听选中变化，写入 registerForm（名称而非编码）
watch(selectedProvinceCode, (newCode) => {
  const province = provinceOptions.value.find(p => String(p.code) === String(newCode))
  registerForm.province = province?.name || ''
  // 上级变更时重置下级
  selectedCityCode.value = ''
  selectedAreaCode.value = ''
  registerForm.city = ''
  registerForm.area = ''
})

watch(selectedCityCode, (newCode) => {
  const city = cityOptions.value.find(c => String(c.code) === String(newCode))
  registerForm.city = city?.name || ''
  // 市变更时重置区
  selectedAreaCode.value = ''
  registerForm.area = ''
})

watch(selectedAreaCode, (newCode) => {
  const area = areaOptions.value.find(a => String(a.code) === String(newCode))
  registerForm.area = area?.name || ''
})

const handleRegister = async ()  =>{
  showRegister.value = true
  const response = await axiosUtil.post('api/store_wechat_login/get_area', {})
  pcaData.value = response.data.data || []
  // 打开时重置联动选择
  selectedProvinceCode.value = ''
  selectedCityCode.value = ''
  selectedAreaCode.value = ''
}

const handleLogin = async () => {
  try {
    const response = await axiosUtil.post('api/index/login', {
      captcha:'',
      host:{},
      username: username.value,
      password: password.value
    })

    if (response.data.code === 1) {
      // 保存token
      LocalStorageUtil.set('token', response.data.data.token, 24 * 60 * 60 * 1000) ;
      LocalStorageUtil.set('id', response.data.data.id, 24 * 60 * 60 * 1000);

      // 保存用户信息到sessionStorage
      sessionStorage.setItem('userInfo', JSON.stringify(response.data.data))

      // 如果选择了记住密码，保存用户名和密码
      if (rememberPassword.value) {
        LocalStorageUtil.set('username', username.value)
        LocalStorageUtil.set('password', password.value)
      } else {
        // 如果没有选择记住密码，清除保存的信息
        LocalStorageUtil.remove('username')
        LocalStorageUtil.remove('password')
      }

      LocalStorageUtil.set('code', username.value)

      // 登录成功提示
      utils.openNotification('success', '登录成功', response.data.msg )

      // 跳转到主页
      console.log('准备跳转到主页...')
      router.push('/ai').then(() => {
        console.log('跳转成功')
      }).catch(err => {
        console.error('跳转失败:', err)
      })
    } else {
      utils.openNotification('error', '登录失败', response.data.msg || '用户名或密码错误')
    }
  } catch (error) {
    // console.log(error)
    utils.openNotification('error', '登录失败', '服务器连接失败，请稍后重试')
  }
}

// 注册相关占位事件，留给你实现
const handleSendCode = async () => {
  try {
    const response = await axiosUtil.post('api/sms_wxl/send', {
      "mobile": registerForm.mobile,
      "event": "register"
    })
    if (response.data.code === 1) {
      utils.openNotification('success', '发送成功', response.data.msg || '验证码已发送')
      return true
    } else {
      utils.openNotification('error', '发送失败', response.data.msg || '发送验证码失败')
      return false
    }
  } catch (error) {
    utils.openNotification('error', '发送失败', '服务器错误，请联系管理员！')
    return false
  }
}

const handleRegisterSubmit = async () => {
  const response = await axiosUtil.post('api/store_wechat_login/register_store', registerForm)
  if (response.data.code === 1) {
    utils.openNotification('success', '注册成功', response.data.msg)
  }else {
    utils.openNotification('error', '注册失败', response.data.msg)
  }

}

const render = (ctx, dots, w, h) => {
  ctx.clearRect(0, 0, w, h);
  ctx.fillStyle = 'rgba(26,94,199,.6)';
  ctx.fillRect(0, 0, w, h);//描绘底层蓝色背景
  for (let i = 0; i < dots.length; i += 1) {
    let dot = dots[i];
    dot.update();
    dot.paint();

  }
  requestAnimationFrame(() => render(ctx, dots, w, h))
}

function init() {
  let canvas = document.querySelector('#canvas') as HTMLCanvasElement;;
  let ctx = canvas.getContext('2d');
  let w = window.innerWidth;//获取屏幕宽高
  let h = window.innerHeight * 2 / 2;
  canvas.width = w;//将屏幕宽高赋值给canvas
  canvas.height = h;
  // canvas.style.cssText += `;width:${w}px;height:${h}px;`;
  let dots = [];
  let minScale = 1;//设置圆点的最小缩放
  let maxScale = 3;//设置圆点的最大缩放
  let bei = 1;
  for (let i = 0; i < 300; i += 1) {  //设置白圆点的个数
    dots.push(new Dot(ctx, w, h, minScale, maxScale))
  }
  render(ctx, dots, w, h);
}

function Dot(this: any, ctx, w, h, minScale, maxScale) {
  this.radius = Math.floor(Math.random() * 3 + 2);//在选一个随机数为圆点半径
  this.d = Math.random() * 2 * Math.PI;//在0-2π之间随机一个弧度值
  this.rx = Math.random() * w * (Math.random() > 0.6 ? 2 / 3 : 1 / 4);// 选一个随机数，作为椭圆长轴顶点a的数值,也就是椭圆中心的x轴坐标，此处的x,y,是相对于椭圆圆心为中心点建立的直角坐标系。
  this.ry = Math.random() * h - h / 2;//选一个随机数作为椭圆短轴顶点b的数值，也就是椭圆中心的y轴坐标，此处的x,y,是相对于椭圆圆心为中心点建立的直角坐标系。这两个值可以根据自已需求来定。
  this.x = Math.cos(this.d) * this.rx + w / 2;
  this.y = Math.sin(this.d) * this.ry + h / 2;//根据椭圆x,y求值公式，x=a*cosα，y=a*sinα.求出圆点在椭圆上的x,y轴坐标.后面加w/2,h/2只是为了居中显示。此处的x,y是相对于canvas建立的直角坐标系的，按canvas约定，其中心点（0,0）点在左上角
  this.z = (Math.pow(Math.pow(this.rx, 2) + Math.pow(this.ry, 2), 0.5) / Math.pow(Math.pow(w / 2, 2) + Math.pow(h / 2, 2), 0.5))//求白色圆点离椭圆中心点的距离，可视为一个点到圆心的距离，用x平方+y平方=c平方求得。此处的x,y,是相对于椭圆圆心为中心点建立的直角坐标系。此处Z值只是一个比值
  this.scale = (Math.cos(this.d) + 1) * (maxScale - minScale) / 2 + minScale;//圆点的缩放大小,根据余弦函数公式y=cosα.标准的余弦函数最大值和最小值分别为1，-1.这里要自行设置最大值和最小值，所以要进行改写
  // this.speed = Math.random() * 0.0005 + 0.0005;
  this.speed = Math.random() * 0.0004 + 0.0004;//圆点运动的速度
  this.alpha = this.scale / maxScale * 0.3 + 0.1;//圆点运动的透明度
  this.count = 0;
  this.paint = () => {
    ctx.fillStyle = 'rgba(0,130,255,' + this.alpha + ')';
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius * this.scale * this.z, 0, Math.PI * 2);
    ctx.fill();
  }
  this.update = () => {
    this.count += 0.01;
    if (Math.floor(this.count) % 12 === 0 && Math.floor(this.count) != 0) {
      this.d += 0.008;
      if (this.count > Math.floor(this.count) + 0.5) {
        this.d -= 0.008;
      }
      // console.log(this.count)
    }


    this.x = Math.sin(this.d) * this.rx + w / 2;
    this.y = Math.cos(this.d) * this.ry + h / 2;
    this.d -= this.speed;//通过改变它的弧度值来改变圆点在椭圆中运动
    this.scale = (Math.cos(this.d) + 1) * (maxScale - minScale) / 2 + minScale;
    this.alpha = this.scale / maxScale * 0.3 + 0.1;
  }
}
</script>
<style scoped>
:global(*) {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  user-select: none;
}

:global(li) {
  list-style-type: none;
}

:global(a) {
  text-decoration: none;
  color: #fff;
}

:global(html) {
  background: #000;
  height: 100%;
}

:global(body) {
  background: #000;
  margin: 0 auto;
  height: 100%;
  position: relative;
  font-family: "PingFang SC", "Lantinghei SC", "Microsoft YaHei", "HanHei SC", "Helvetica Neue", "Open Sans", Arial, "Hiragino Sans GB", "微软雅黑", STHeiti, "WenQuanYi Micro Hei", SimSun, sans-serif;
}

:global(body::before) {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url(../assets/images/bg.png) no-repeat left center;
  content: "";
  left: 0;
  top: 0;
  z-index: 100;
  pointer-events: none;
}

/* 确保登录页面背景图不受其他页面影响 */
:global(body.login-page) {
  background: #000 !important;
}

:global(body.login-page::before) {
  display: block !important;
}

.loginbg {
  background-image: linear-gradient(300deg, #004491, #1e88e5);
  position: absolute;
  width: 100%;
  height: 50%;
  left: 0;
  top: 0;
  z-index: 0
}

.loginav {
  max-width: 1300px;
  width: 100%;
  height: 100%;
  margin: 0 auto;
  z-index: 10;
  box-shadow: 0 0 30px rgba(0, 0, 0, .1);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.video {
  top: 65px;
  position: absolute;
  width: 1200px;
  left: 0px;
  padding-bottom: 40px;
  pointer-events: none;
}

.video video {
  width: 100%;
}

.video::before {
  position: absolute;
  content: "";
  width: 200px;
  height: 100%;
  background: #000;
  right: 0;
  top: 0;
}

.logotit {
  text-align: center;
  padding: 40px 0;
  font-size: 30px
}

.loginbox {
  padding: 30px 0 50px 0;
  width: 600px;
  padding: 30px 50px;
  flex-shrink: 0;
  position: relative;
  margin-top: 200px;
  z-index: 100;
}

.logininput .forminput {
  border: 2px solid rgba(32, 163, 245, .4);
  font-family: "PingFang SC", "Lantinghei SC", "Microsoft YaHei", "HanHei SC", "Helvetica Neue", "Open Sans", Arial, "Hiragino Sans GB", "微软雅黑", STHeiti, "WenQuanYi Micro Hei", SimSun, sans-serif;
  display: block;
  padding-left: 50px;
  font-size: 18px;
  color: #fff;
  width: 100%;
  line-height: 48px;
  outline: 0;
  text-indent: 1px;
  background: rgba(32, 163, 245, .1);
}

input::input-placeholder {
  color: #fff;
}

::-webkit-input-placeholder {
  color: #fff;
}


.flex1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flex1 label {
  color: #fff;
  display: flex;
  align-items: center;
}

.logininput>li {
  display: block;
  padding: 15px 0;
  position: relative;
}

.logininput li>i {
  position: absolute;
  height: 100%;
  left: 15px;
  top: 0;
  display: flex;
  align-items: center;
}

.logintit {
  color: #00bff4;
  text-align: center;
  position: relative;
  padding: 25px 0;
  font-size: 24px
}

.btn-primary {
  background: #20a3f5;
  display: block;
  text-align: center;
  color: #fff;
  line-height: 48PX;
  font-size: 24px;
}

.btn-primary:hover {
  background: #137bd6
}

.btn-row {
  display: flex;
  gap: 16px;
}

.btn-row .btn-primary {
  flex: 1;
  width: 100%;
}

/* 验证码输入+发送 按钮组 */
.verify-row {
  display: flex;
  align-items: center;
  gap: 12px;
}
.verify-row .forminput {
  flex: 1;
  width: auto;
}
.verify-row .send-btn {
  white-space: nowrap;
  padding: 0 16px;
}

/* 注册弹窗紧凑布局，仅作用于弹窗 */
.register-wrap .logintit {
  padding: 10px 0;
  font-size: 20px;
}
.register-wrap .logininput>li {
  padding: 8px 0;
}
.register-wrap .forminput {
  line-height: 40px;
  font-size: 16px;
}
.register-wrap .btn-row {
  gap: 8px;
}
.register-wrap .verify-row {
  gap: 8px;
}
/* 弹窗内按钮字号与高度更协调 */
.register-wrap .btn-primary,
.register-wrap .send-btn {
  font-size: 16px;
  line-height: 40px;
}
/* 保持发送验证码小号按钮；提交按钮使用原有整行样式 */

/* 统一下拉与弹出选项区域底色，与 forminput 一致 */
.register-wrap select.forminput {
  background: rgba(32, 163, 245, .1);
  color: #000;
}
.register-wrap select.forminput option {
  background: rgba(32, 163, 245, .1);
  color: #000;
}
.register-wrap select.forminput option[disabled] {
  color: #9aa0a6;
}

/* 下拉滚动条美化（与底色统一） */
.register-wrap select.forminput {
  scrollbar-color: #20a3f5 rgba(32, 163, 245, .1); /* Firefox: 滑块/轨道 */
  scrollbar-width: thin; /* Firefox */
}
.register-wrap select.forminput::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}
.register-wrap select.forminput::-webkit-scrollbar-track {
  background: rgba(32, 163, 245, .1);
}
.register-wrap select.forminput::-webkit-scrollbar-thumb {
  background: #20a3f5;
  border-radius: 8px;
}
.register-wrap select.forminput::-webkit-scrollbar-thumb:hover {
  background: #137bd6;
}

/* （恢复默认） */

.copyright {
  position: fixed;
  width: 100%;
  left: 0;
  bottom: 10px;
  text-align: center;
  color: #006b95;
  font-size: 12px
}

.logo {
  position: absolute;
  top: -120px;
  width: 100%;
  left: 0;
  text-align: center;
  color: #fff;
}

.logo h1,
.logo h2 {
  background: linear-gradient(90deg, #009ef3, #00e9d0);
  background-size: cover;
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  text-fill-color: transparent;
}

.logo h1 {
  font-weight: bolder;
  font-size: 48px;
  font-family: "Microsoft YaHei", "HanHei SC";
  letter-spacing: 2px;
}

.logo h2 {
  font-size: 30px;
  text-transform: uppercase;
  font-weight: lighter;
  letter-spacing: 2px;
}

.boxall {
  border: 2px solid #186baf;
  background: rgba(32, 163, 245, .1);
  position: relative;
  transform: scale(.7);
  opacity: 0;
  animation: shows 1s forwards;
}

@keyframes shows {
  to {
    transform: scale(1);
    opacity: 1;
  }
}

.boxall:before,
.boxall:after {
  position: absolute;
  width: 30px;
  height: 30px;
  content: "";
  border-top: 3px solid #20a3f5;
  top: -2px;
}

.boxall:before,
.boxfoot:before {
  border-left: 3px solid #20a3f5;
  left: -2px;
}

.boxall:after,
.boxfoot:after {
  border-right: 3px solid #20a3f5;
  right: -2px;
}

.boxfoot {
  position: absolute;
  bottom: 0;
  width: 100%;
  left: 0;
}

.boxfoot:before,
.boxfoot:after {
  position: absolute;
  width: 30px;
  height: 30px;
  content: "";
  border-bottom: 3px solid #20a3f5;
  bottom: -2px;
}


.aui-checkbox,
input[type=radio] {
  width: 24px;
  height: 24px;
  background: rgba(32, 163, 245, .1);
  border: solid 2px rgba(32, 163, 245, .5);
  margin: 0;
  padding: 0;
  position: relative;
  cursor: default;
  -webkit-appearance: none;
  -webkit-user-select: none;
  user-select: none;
  -webkit-transition: background-color ease .1s;
  transition: background-color ease .1s;
  flex-shrink: 0;
  border-radius: 0;
}

.aui-checkbox,
input[type=radio] {
  margin: 0 3px 0 0 !important;
  position: relative;
}

.aui-checkbox:checked,
input[type=radio]:checked {
  text-align: center;
  background-clip: padding-box;
}

.aui-checkbox:checked:after,
.aui-checkbox:checked:before,
input[type=radio]:checked:after,
input[type=radio]:checked:before {
  content: '';
  width: 10px;
  height: 5px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -6px;
  margin-top: -5px;
  background: 0 0;
  border: 2px solid #439aff;
  border-top: none;
  border-right: none;
  z-index: 2;
  -webkit-border-radius: 0;
  border-radius: 0;
  -webkit-transform: rotate(-45deg);
  transform: rotate(-45deg)
}

.aui-checkbox:disabled,
input[type=radio]:disabled {
  background-color: #f5f5f5;
  border: solid 1px #ddd
}

.aui-checkbox:disabled:after,
.aui-checkbox:disabled:before,
input[type=radio]:disabled:after,
input[type=radio]:disabled:before {
  content: '';
  width: .5rem;
  height: .3rem;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -.25rem;
  margin-top: -.4rem;
  background: 0 0;
  border: 1px solid #fff;
  border-top: none;
  border-right: none;
  z-index: 2;
  -webkit-border-radius: 0;
  border-radius: 0;
  -webkit-transform: rotate(-45deg);
  transform: rotate(-45deg)
}

input[type="radio"] {
  border-radius: 20px;
}

input {
  outline: none !important;
}



@media (max-width: 1200px) {
  .loginav {
    justify-content: center;
  }

  .video {
    display: none;
  }

  .loginbox {
    width: 96%;
  }

  .logo h1 {
    font-size: 30px;
  }

  .logo h2 {
    font-size: 20px;
  }

  .loginbox {
    padding: 30px;
  }
}
</style>
